import time, os, django, ast
from datetime import datetime
from templates.getHourlyWeather import Hourly_weather
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "get_weather.settings")  # project_name 项目名称
django.setup()
from API_getWeather.models import *
from templates.getTodayWeather import today_weather
from templates.logger import Loggers

"""定时函数执行:1.查询数据库最新的一条数据的code;
                2.code作为save**的参数,如果数据库没得数据,执行save 异常list index out of range"""


class querySave:
    def __init__(self):
        global logger
        logger = Loggers().make_logger('savaDatas')

    def saveByToday(self):  # 1小时爬取一次当天天气并保存
        logger.info('Start today saveToday timing loading......')
        code = self.queryFristCodeByToday()  # 获取mysql中最新的天气数据city_code
        result = today_weather().start(code)
        if result['cityCode'] is '':
            logger.warning('weather_today(table) is null')
        else:
            contents = todayDatas(city_code=result['cityCode'], city_name=result['cityName'],
                                  datas=result['contents'])  # 保存数据
            contents.save()
        logger.info('saveToday successful')

    def queryCreateTimeByToday(slef, city_code):  # 获取数据存库时间时间
        query_result = todayDatas.objects.filter(city_code=city_code).order_by('-create_time')
        result = query_result.values()
        try:
            create_time = result[0]['create_time']  # 存在
        except:
            create_time = None  # 为空
        return create_time

    def queryContentsByToday(self, city_code):  # 查询今日数据
        query_result = todayDatas.objects.filter(city_code=city_code).order_by('-create_time')
        result = query_result.values()[0]
        contents = [content for content in result.values()]
        return contents[1:len(contents) - 1]

    def queryFristCodeByToday(self):  # 获取最新mysql存储的city_code,用于定时爬取
        code = ''
        try:
            query_result = todayDatas.objects.filter().order_by('-create_time')
            code = query_result.values()[0]['city_code']
        except:
            logger.warning('database is null')
        return code

    # ####整点概况###################################################################################
    def savaByHours(self):
        logger.info('Start hours clmib loading......')

        code = self.queryFristCodeByHours()
        result = Hourly_weather().start(code)
        if result['cityCode'] is '':
            logger.warning('weather_hours is null ')
        else:
            mysql_datas = hoursDatas(city_code=result['cityCode'], city_name=result['address'], aqi=result['hourAQI'],
                                     temperature=result['hourTe'],
                                     humidity=result['hourHu'], wind=result['hourWind'])
            mysql_datas.save()
        logger.info('saveHours successful')

    def queryCreateTimeByHours(slef, city_code):  # 获取数据存库时间时间
        query_result = hoursDatas.objects.filter(city_code=city_code).order_by('-create_time')
        result = query_result.values()
        try:
            create_time = result[0]['create_time']  # 存在
        except:
            create_time = None  # 为空
        return create_time

    def queryContentsByHours(self, city_code):
        query_result = hoursDatas.objects.filter(city_code=city_code).order_by('-create_time')
        result = query_result.values()[0]
        contents = [vaule for vaule in result.values()]
        return contents[1:len(contents) - 1]  # 返回排除了id,create_time

    def queryFristCodeByHours(self):
        try:
            query_result = hoursDatas.objects.filter().order_by('-create_time')
            code = query_result.values()[0]['city_code']
            return code
        except:
            logger.info('null')


class queryCode:
    def __init__(self):
        global logger
        logger = Loggers().make_logger('queryCode')
    def queryCityCode(self, name):
        result = cityCodes.objects.filter().order_by('-id')  # 通过id降序查询所有的内容
        new_result = result.values()[0]['all_code']  # 获取到所有的code
        query_result = ast.literal_eval(new_result)  # ast.literal_eval将str转为dict
        try:
            code = query_result[name]
            return code
        except:
            logger.error("查询的地区不存在,请输入对应市/区. 注: 查询市/区,不需要输入市/区.如:查询'成都市',只需输入'成都'. ")


class deleteDatas:
    # 只会保留一天的数据
    def delByToday(self):
        today = datetime.now().strftime('%d')
        delDatas = todayDatas.objects.filter().values()
        for i in delDatas:
            # 将其转为时间数组
            day = i['create_time'].strftime('%d')
            if day < today:
                todayDatas.objects.filter(create_time__day=day).delete()
            elif (day == '30' or day == '31') and today == '01':
                todayDatas.objects.filter(create_time__day=day).delete()
            else:
                pass

    def delByHours(self):
        today = datetime.now().strftime('%d')
        delDatas = hoursDatas.objects.filter().values()
        for i in delDatas:
            # 将其转为时间数组
            day = i['create_time'].strftime('%d')
            if day < today:
                hoursDatas.objects.filter(create_time__day=day).delete()
            elif (day == '30' or day == '31') and today == '01':
                hoursDatas.objects.filter(create_time__day=day).delete()
            else:
                pass


if __name__ == '__main__':
    # m = querySave().queryContentsByToday(101270101)
    # print(m)
    querySave().saveByToday()
    # t = queryCode().queryCityCode('香港')
    # print(t)
    # deleteDatas().delByHours()
    # querySave().saveByToday()
    # t = querySave().savaByHours()
    # t = querySave().queryFristCodeByHours()
    # print(t)
